// 通常可以把 baseUrl 单独放在一个 js 文件了
import sign from '@/utils/signature'
// 程佳
// const baseUrl= 'http://192.168.0.188:9029/'
// 张建文
// const baseUrl = 'http://192.168.0.56:8172'
// 正式
const baseUrl = 'https://ykj.java.68hanchen.com/api-client'
let loading
//内存中正在请求的数量
let loadingNum = 0
function startLoading() {
  if (loadingNum == 0) {
    uni.showLoading({
      mask: true
    })
  }
  //请求数量加1
  loadingNum++
}

function endLoading() {
  //请求数量减1
  loadingNum--
  if (loadingNum <= 0) {
    console.log('当前还有几个请求在走->', loadingNum)
    uni.hideLoading()
  }
}
const request = (options = { header: {} }) => {
  if (options.url !== '/client-user/getQrCode') {
    startLoading()
  }
  let tokenName = uni.getStorageSync('tokenName') || ''
  let tokenValue = uni.getStorageSync('tokenValue') || ''
  let con_type = options.qs ? 'application/json' : 'application/x-www-form-urlencoded'
  options.header = {
    'Content-Type': con_type
  }
  if (tokenName) {
    options.header[tokenName] = tokenValue
  }
  sign.configure(options)
  return new Promise((resolve, reject) => {
    uni
      .request({
        url: baseUrl + options.url || '',
        method: options.type || 'GET',
        data: options.data || {},
        header: options.header || {}
      })
      .then((res) => {
        if (options.url !== '/client-user/getQrCode') {
          endLoading()
        }
        if (res.data.code == 100 || res.data.code == 101) {
          // 状态码为1xx
          uni.showToast({
            title: '请先登录',
            icon: 'none',
            duration: 2000
          })
          uni.navigateTo({
            url: '/pages/login/login'
          })
          uni.removeStorageSync('tokenValue')
        } else if (res.data.code == 200 || res.data.code == 302) {
          resolve(res.data)
        } else {
          uni.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 2000
          })
          resolve(res)
        }
      })
      .catch((error) => {
        if (options.url !== '/client-user/getQrCode') {
          endLoading()
        }
        reject(error)
      })
  })
}
export default request
